package com.houtai.aclservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.houtai.aclservice.entity.AclPermission;
import com.houtai.aclservice.entity.AclRolePermission;
import com.houtai.aclservice.entity.AclUser;
import com.houtai.aclservice.helper.MemuHelper;
import com.houtai.aclservice.helper.PermissionHelper;
import com.houtai.aclservice.mapper.AclPermissionMapper;
import com.houtai.aclservice.service.AclPermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.houtai.aclservice.service.AclRolePermissionService;
import com.houtai.aclservice.service.AclUserService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lin
 * @since 2022-12-11
 */
@Service
public class AclPermissionServiceImpl extends ServiceImpl<AclPermissionMapper, AclPermission> implements AclPermissionService {

    @Autowired
    public AclRolePermissionService aclRolePermissionService;
    @Autowired
    public AclUserService aclUserService;
    //递归查询
    @Override
    public List<AclPermission> queryAllMenu() {
        QueryWrapper<AclPermission> wrapper=new QueryWrapper<>();
        wrapper.orderByDesc("id");
        List<AclPermission>permissionList=baseMapper.selectList(wrapper);
        List<AclPermission> resultList=buildPermission(permissionList);
        return resultList;
    }

    //把返回所有菜单list集合进行封装的方法
    public static List<AclPermission> buildPermission(List<AclPermission> permissionList) {

        //创建list集合，用于数据最终封装
        List<AclPermission> finalNode = new ArrayList<>();
        //把所有菜单list集合遍历，得到顶层菜单 pid=0菜单，设置level是1
        for(AclPermission permissionNode : permissionList) {
            //得到顶层菜单 pid=0菜单
            if("0".equals(permissionNode.getPid())) {
                //设置顶层菜单的level是1
                permissionNode.setLevel(1);
                //根据顶层菜单，向里面进行查询子菜单，封装到finalNode里面
                finalNode.add(selectChildren(permissionNode,permissionList));
            }
        }
        return finalNode;
    }
    private static AclPermission selectChildren(AclPermission permissionNode, List<AclPermission> permissionList) {
        //1 因为向一层菜单里面放二层菜单，二层里面还要放三层，把对象初始化
        permissionNode.setChildren(new ArrayList<AclPermission>());

        //2 遍历所有菜单list集合，进行判断比较，比较id和pid值是否相同
        for(AclPermission i : permissionList) {
            //判断 id和pid值是否相同
            if(permissionNode.getId().equals(i.getPid())) {
                //把父菜单的level值+1
                int level = permissionNode.getLevel()+1;
                i.setLevel(level);
                //如果children为空，进行初始化操作
                if(permissionNode.getChildren() == null) {
                    //初始化操作
                    permissionNode.setChildren(new ArrayList<AclPermission>());
                }
                //把查询出来的子菜单放到父菜单里面
                permissionNode.getChildren().add(selectChildren(i,permissionList));
            }
        }
        return permissionNode;
    }

    //递归删除菜单
    @Override
    public void removeChildById(String id) {
        //1.创建集合，封装所有需要删除的id值
        List<String> idList=new ArrayList<>();
        //2.向集合中传入id
        this.selPermissionIds(id,idList);
        //把当前id封装到List中去
        idList.add(id);
        baseMapper.deleteBatchIds(idList);

    }
    //2.根据id，查询子菜单id
    private void selPermissionIds(String id,List<String> idList){
        QueryWrapper<AclPermission> wrapper=new QueryWrapper<>();
        wrapper.eq("pid",id);
        wrapper.select("id");
        List<AclPermission> childList=baseMapper.selectList(wrapper);
        //把childIdList里面菜单id值获取出来，封装idList里面，做递归查询
        childList.stream().forEach(item -> {
            //封装idList里面
            idList.add(item.getId());
            //递归查询
            this.selPermissionIds(item.getId(),idList);
        });

    }

    //给角色分配菜单
    @Override
    public void saveRolePermission(String roleId, String[] permissionId) {
        //1.创建集合，封装数据
        List<AclRolePermission> rolePermissionList=new ArrayList<>();
//        //2.手动加上父节点
//        AclRolePermission aclRolePermission1=new AclRolePermission();
//        aclRolePermission1.setPermissionId("1");
//        aclRolePermission1.setRoleId(roleId);
//        rolePermissionList.add(aclRolePermission1);
        //2.遍历数组（增强for循环）
        for(String perId:permissionId){
            AclRolePermission aclRolePermission=new AclRolePermission();
            aclRolePermission.setRoleId(roleId);
            aclRolePermission.setPermissionId(perId);
            //3.封装到list集合
            rolePermissionList.add(aclRolePermission);
        }
        //4.添加到数据库中
        aclRolePermissionService.saveBatch(rolePermissionList);

    }

    @Override
    public List<AclPermission> selectAllMenu(String roleId) {
        List<AclPermission> allPermissionList = baseMapper.selectList(new QueryWrapper<AclPermission>().orderByAsc("CAST(id AS SIGNED)"));

        //根据角色id获取角色权限
        List<AclRolePermission> rolePermissionList = aclRolePermissionService.list(new QueryWrapper<AclRolePermission>().eq("role_id",roleId));
        //转换给角色id与角色权限对应Map对象
//        List<String> permissionIdList = rolePermissionList.stream().map(e -> e.getPermissionId()).collect(Collectors.toList());
//        allPermissionList.forEach(permission -> {
//            if(permissionIdList.contains(permission.getId())) {
//                permission.setSelect(true);
//            } else {
//                permission.setSelect(false);
//            }
//        });
        for (int i = 0; i < allPermissionList.size(); i++) {
            AclPermission permission = allPermissionList.get(i);
            for (int m = 0; m < rolePermissionList.size(); m++) {
                AclRolePermission rolePermission = rolePermissionList.get(m);
                if(rolePermission.getPermissionId().equals(permission.getId())) {
                    permission.setSelect(true);
                }
            }
        }
        List<AclPermission> permissionList = buildPermission(allPermissionList);
        return permissionList;

    }

    /**
     * 判断用户是否系统管理员
     * @param userId
     * @return
     */
    private boolean isSysAdmin(String userId) {
        AclUser user = aclUserService.getById(userId);

        if(null != user && "admin".equals(user.getUsername())) {
            return true;
        }
        return false;
    }

    //根据用户id获取用户菜单
    @Override
    public List<String> selectPermissionValueByUserId(String id) {

        List<String> selectPermissionValueList = null;
        if(this.isSysAdmin(id)) {
            //如果是系统管理员，获取所有权限
            selectPermissionValueList = baseMapper.selectAllPermissionValue();
        } else {
            selectPermissionValueList = baseMapper.selectPermissionValueByUserId(id);
        }
        return selectPermissionValueList;
    }

    @Override
    public List<JSONObject> selectPermissionByUserId(String id) {
        List<AclPermission> selectPermissionList = null;
        if(this.isSysAdmin(id)) {
            //如果是超级管理员，获取所有菜单
            selectPermissionList = baseMapper.selectList(null);
        } else {
            selectPermissionList = baseMapper.selectPermissionByUserId(id);
        }

        List<AclPermission> permissionList = PermissionHelper.build(selectPermissionList);
        List<JSONObject> result = MemuHelper.bulid(permissionList);
        return result;
    }
}
